<?php

namespace my\kaoqin;

class KaoQin
{
    const API_URL_PREFIX = 'http://open.iquanqin.com/develop';

    const TOKEN_GET_URL = '/accessToken/get?';

    const OAUTH_LOGIN_URL = '/oauth/login'; // 一键登录

    const DEPT_LIST_URL = '/dept/list'; //部门列表
    const DEPT_ADD_URL = '/dept/add'; //新增部门
    const DEPT_UPDATE_URL = '/dept/update'; //修改部门
    const DEPT_DELETE_URL = '/dept/delete'; //删除部门

    const USER_LIST_URL = '/user/list'; //员工列表
    const USER_ADD_URL = '/user/add'; //新增员工
    const USER_UPDATE_URL = '/user/update'; //修改员工
    const USER_DELETE_URL = '/user/delete'; //删除员工

    private $appid;         //开发者 appId
    private $companyid;         //企业号
    private $appsecret;
    private $access_token;
    private $token;   //sign 中 token 为用户自定义数据加密 key(可选)
    public $debug = false;
    public $errCode = 0;
    public $errMsg = "";

    private $get_access_token_times = 0;    //获取access_token次数

    public function __construct($options)
    {
        $this->token = isset($options['token']) ? $options['token'] : '';
        $this->appid = isset($options['appid']) ? $options['appid'] : '';
        $this->companyid = isset($options['companyid']) ? $options['companyid'] : '';
        $this->appsecret = isset($options['appsecret']) ? $options['appsecret'] : '';
    }

    /**
     * 微信api不支持中文转义的json结构
     * @param $arr
     * @return string
     * @author wb <pithyone@vip.qq.com>
     */
    static function json_encode($arr)
    {
        $parts = array();
        $is_list = false;
        //Find out if the given array is a numerical array
        $keys = array_keys($arr);
        $max_length = count($arr) - 1;
        if (($keys [0] === 0) && ($keys [$max_length] === $max_length)) { //See if the first key is 0 and last key is length - 1
            $is_list = true;
            for ($i = 0; $i < count($keys); $i++) { //See if each key correspondes to its position
                if ($i != $keys [$i]) { //A key fails at position check.
                    $is_list = false; //It is an associative array.
                    break;
                }
            }
        }
        foreach ($arr as $key => $value) {
            if (is_array($value)) { //Custom handling for arrays
                if ($is_list)
                    $parts [] = self::json_encode($value); /* :RECURSION: */
                else
                    $parts [] = '"' . $key . '":' . self::json_encode($value); /* :RECURSION: */
            } else {
                $str = '';
                if (!$is_list)
                    $str = '"' . $key . '":';
                //Custom handling for multiple data types
                if (!is_string($value) && is_numeric($value) && $value < 2000000000)
                    $str .= $value; //Numbers
                elseif ($value === false)
                    $str .= 'false'; //The booleans
                elseif ($value === true)
                    $str .= 'true';
                else
                    $str .= '"' . addcslashes($value, "\\\"\n\r\t/") . '"'; //All other things
                $parts [] = $str;
            }
        }
        $json = implode(',', $parts);
        if ($is_list)
            return '[' . $json . ']'; //Return numerical JSON
        return '{' . $json . '}'; //Return associative JSON
    }

    /**
     * GET 请求
     * @param $url
     * @return bool|mixed
     * @author wb <pithyone@vip.qq.com>
     */
    private function http_get($url)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }

    /**
     * POST 请求
     * @param string $url
     * @param array $param
     * @param boolean $post_file 是否文件上传
     * @return string content
     */
    private function http_post($url, $param, $post_file = false)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (is_string($param) || $post_file) {
            $strPOST = $param;
        } else {
            $strPOST = http_build_query($param);
        }
        trace('$url=' . $url);
        trace('$url-param=' . json_encode($strPOST));
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
        curl_setopt($oCurl, CURLOPT_HTTPHEADER, ['Content-Type: application/json; charset=utf-8']);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }

    /**
     * 重载设置缓存
     * @param string $cachename
     * @param mixed $value
     * @param int $expired
     * @return boolean
     */
    protected function setCache($cachename, $value, $expired)
    {
        return cache($cachename, $value, $expired);
    }

    /**
     * 重载获取缓存
     * @param string $cachename
     * @return mixed
     */
    protected function getCache($cachename)
    {
        return cache($cachename);
    }

    /**
     * 重载清除缓存
     * @param string $cachename
     * @return boolean
     */
    protected function removeCache($cachename)
    {
        return cache($cachename, null);
    }

    /**
     * HTTP 请求基本数据
     * @return array
     * @author wb <pithyone@vip.qq.com>
     */
    public function baseHttpData()
    {
        $timestamp = time();
        $sign = md5($this->access_token . $timestamp . $this->token);

        $data = [
            'access_token' => $this->access_token,
            'timestamp' => $timestamp,
            'sign' => $sign,
        ];

        return $data;
    }

    /**
     * HTTP POST返回结果
     * @param $url
     * @param array $data
     * @return bool|mixed
     * @author wb <pithyone@vip.qq.com>
     */
    public function httpPostRet($url, $data = [])
    {
        if (!$this->access_token && !$this->checkAuth()) return false;

        $data = self::json_encode(array_merge($this->baseHttpData(), $data));

        $result = $this->http_post($url, $data);
        if ($result) {
            $json = json_decode($result, true);
            if (!$json)
                return false;

            if (isset($json['code']) && $json['code'] != 0) {
                if ($json['code'] == 70101 || $json['code'] == 70102) {
                    $authname = 'kaoqin_access_token' . $this->appid;
                    $this->removeCache($authname);
                    $this->get_access_token_times++;
                    if ($this->get_access_token_times < 2) $this->httpPostRet($url);
                }
                $this->errCode = $json['code'];
                $this->errMsg = KqErrCode::getErrText($json['code']);
                return false;
            }
            return $json;
        }
        return false;
    }

    /**
     * 通用auth验证方法
     * @return bool|mixed
     * @author wb <pithyone@vip.qq.com>
     */
    public function checkAuth()
    {

        $authname = 'kaoqin_access_token' . $this->appid;

        if ($rs = $this->getCache($authname)) {
            $this->access_token = $rs;
            return $rs;
        }

        $timestamp = time();
        $sign = md5($this->appid . $this->appsecret . $this->companyid . $timestamp . $this->token);

        $result = $this->http_get(self::API_URL_PREFIX . self::TOKEN_GET_URL . 'appId=' . $this->appid . '&companyId=' . $this->companyid . '&timestamp=' . $timestamp . '&sign=' . $sign);
        if ($result) {

            $json = json_decode($result, true);
            if (!$json)
                return false;

            if (isset($json['code']) && $json['code'] != 0) {
                $this->errCode = $json['code'];
                $this->errMsg = KqErrCode::getErrText($json['code']);
                return false;
            }

            $this->access_token = $json['access_token'];
            $expire = $json['time'] ? intval($json['time']) - 100 : 3600;
            $this->setCache($authname, $this->access_token, $expire);
            return $this->access_token;
        }
        return false;
    }

    /**
     * WEB 一键登录
     * @return bool|mixed
     * @author wb <pithyone@vip.qq.com>
     */
    public function oauth()
    {
        $url = self::API_URL_PREFIX . self::OAUTH_LOGIN_URL;
        return $this->httpPostRet($url);
    }

    /**
     * 部门列表
     * @return bool|mixed
     * @author wb <pithyone@vip.qq.com>
     */
    public function deptList()
    {
        $url = self::API_URL_PREFIX . self::DEPT_LIST_URL;
        return $this->httpPostRet($url);
    }

    /**
     * 新增部门，支持批量
     * @param $data
     * @return bool|mixed
     * @author wb <pithyone@vip.qq.com>
     */
    public function deptAdd($data)
    {
        $url = self::API_URL_PREFIX . self::DEPT_ADD_URL;
        return $this->httpPostRet($url, $data);
    }

    /**
     * 修改部门
     * @param $data
     * @return bool|mixed
     * @author wb <pithyone@vip.qq.com>
     */
    public function deptUpdate($data)
    {
        $url = self::API_URL_PREFIX . self::DEPT_UPDATE_URL;
        return $this->httpPostRet($url, $data);
    }

    /**
     * 删除部门，支持批量
     * @param $data
     * @return bool|mixed
     * @author wb <pithyone@vip.qq.com>
     */
    public function deptDelete($data)
    {
        $url = self::API_URL_PREFIX . self::DEPT_DELETE_URL;
        return $this->httpPostRet($url, $data);
    }

    /**
     * 员工列表
     * @return bool|mixed
     * @author wb <pithyone@vip.qq.com>
     */
    public function userList()
    {
        $url = self::API_URL_PREFIX . self::USER_LIST_URL;
        return $this->httpPostRet($url);
    }

    /**
     * 新增员工，支持批量
     * @param $data
     * @return bool|mixed
     * @author wb <pithyone@vip.qq.com>
     */
    public function userAdd($data)
    {
        $url = self::API_URL_PREFIX . self::USER_ADD_URL;
        return $this->httpPostRet($url, $data);
    }

    /**
     * 修改员工
     * @param $data
     * @return bool|mixed
     * @author wb <pithyone@vip.qq.com>
     */
    public function userUpdate($data)
    {
        $url = self::API_URL_PREFIX . self::USER_UPDATE_URL;
        return $this->httpPostRet($url, $data);
    }

    /**
     * 删除员工，支持批量
     * @param $data
     * @return bool|mixed
     * @author wb <pithyone@vip.qq.com>
     */
    public function userDelete($data)
    {
        $url = self::API_URL_PREFIX . self::USER_DELETE_URL;
        return $this->httpPostRet($url, $data);
    }
}